import json

import pymongo
from urllib import parse

# 测试连接
# import pymongo
# try:
#     client = pymongo.MongoClient("mongodb://118.178.190.198:27017/", serverSelectionTimeoutMS=3000)
#     client.admin.command('ping')
#     print("MongoDB 服务器可用")
# except Exception as e:
#     print("连接失败:", e)

# 编码用户名密码
username = parse.quote_plus('admin')
password = parse.quote_plus('123456')
database = "mongo"  # 认证数据库
host = "118.178.190.198"
port = "27017"

# 建立连接
client = pymongo.MongoClient(
    f'mongodb://{username}:{password}@{host}:{port}/{database}',
    authSource="admin",
    authMechanism="SCRAM-SHA-256"
)

# 选择要操作的数据库（不是认证数据库）
db = client["mongo"]  # 数据库名

# 选择集合（相当于SQL的表）
# collection = db["my_collection"]
collection = db["my_talk"]

def getconnection():
    data = []
    for doc in collection.find():
        doc.pop('_id', None)
        data.append(doc)
    return data


def getone(sid):
    # 构建查询条件：匹配字符串或数字形式的 sid
    or_conditions = [{"sid": sid}]

    try:
        # 尝试添加数字形式的查询条件
        or_conditions.append({"sid": int(sid)})
    except ValueError:
        pass  # 如果 sid 不是数字字符串，则跳过

    # 使用 $or 查询所有可能的匹配
    cursor = collection.find({"$or": or_conditions})

    # 转换为列表并移除 _id 字段
    results = []
    for doc in cursor:
        doc.pop('_id', None)  # 移除 MongoDB 默认的 _id 字段
        results.append(doc)

    return results if results else None

def postone(document):
    collection.insert_one(document)
def deleteone(name):
    query = {"nickname": name}
    collection.delete_many(query)









# 插入单个文档
# document = {"name": "王五", "age": 25, "city": "北京"}
# insert_result = collection.insert_one(document)
# print(f"插入文档ID: {insert_result.inserted_id}")

# 插入多个文档
# documents = [
#     {"name": "李四", "age": 30, "city": "上海"},
#     {"name": "王五", "age": 35, "city": "广州"}
# ]
# insert_many_result = collection.insert_many(documents)
# print(f"插入的文档IDs: {insert_many_result.inserted_ids}")

# 查询单个文档
# print("查询单个文档:")
# print(collection.find_one({"name": "马成"}))

# 查询所有文档
# print("查询所有文档:")
# for doc in collection.find():
#     print(doc)

# 条件查询
# print("年龄大于28的用户:")
# for doc in collection.find({"age": {"$gt": 28}}):
#     print(doc)

# 使用 my_mongodb.py 中的 MongoDB 连接配置
# from my_mongodb import client, db, collection
# import json


# def insert_movie_comments_to_mongodb(file_path: str):
#     """
#     将电影评论数据插入MongoDB
#     :param file_path: 评论JSON文件路径
#     """
#     try:
#         # 1. 读取评论数据
#         with open(file_path, 'r', encoding='utf-8') as f:
#             comments = json.load(f)
#
#         # 2. 插入数据到MongoDB
#         if isinstance(comments, list):
#             # 批量插入
#             result = collection.insert_many(comments)
#             print(f"成功插入 {len(result.inserted_ids)} 条评论")
#         else:
#             # 单条插入
#             result = collection.insert_one(comments)
#             print(f"成功插入1条评论，ID: {result.inserted_id}")
#
#         # 3. 添加索引优化查询性能
#         collection.create_index([("user_id", pymongo.ASCENDING)])
#         collection.create_index([("score", pymongo.DESCENDING)])
#         collection.create_index([("tags", pymongo.ASCENDING)])
#         print("已创建查询索引")
#
#     except Exception as e:
#         print(f"插入数据失败: {e}")
#
#
# def query_comments_examples():
#     """查询示例"""
#     print("\n查询示例结果:")
#
#     # 1. 查询评分5分的评论
#     print("\n1. 评分5分的评论:")
#     for doc in collection.find({"score": 5.0}).limit(3):
#         print(f"{doc['nickname']}: {doc['content'][:50]}...")
#
#     # 2. 查询包含IMAX标签的评论
#     print("\n2. IMAX体验评论:")
#     for doc in collection.find({"tags": "imax"}).limit(3):
#         print(f"{doc['nickname']} (点赞: {doc['approve']}): {doc['content'][:50]}...")
#
#     # 3. 查询点赞数超过100的热门评论
#     print("\n3. 热门评论(点赞>100):")
#     for doc in collection.find({"approve": {"$gt": 100}}).sort("approve", -1).limit(3):
#         print(f"{doc['nickname']} (点赞: {doc['approve']}): {doc['content'][:50]}...")


# if __name__ == "__main__":
#     # 插入数据
#     # insert_movie_comments_to_mongodb("talk_text_1454962.txt")
#
#     # 查询示例
#     query_comments_examples()
#
#     # 关闭连接
#     client.close()






